/* 有获取表格数据的页面的通用逻辑
 * 需要提供 - preFetchTableData - 获取当前页面表格数据接口
-------------------------- */
import { mapState } from 'vuex'

const tableCoreMixin = {
  data () {
    return {
      tableData: null,
      tableTotal: 0,
      sort_field: '',
      sort_type: '',
      page: '1',
      pageSize: '5',
      pageSizes: [5, 10, 20, 50],
      tableLoading: false,
      selectList: [],
      selectIds: '',  // 已选择的ids,用于接口参数需要
      paginationBySelf: false, // 是否前端自己分页
      allData: []
    }
  },
  computed: {
    ...mapState([ 'pageSearchHistory' ]),
    componentName () {
      return this.constructor.extendOptions.name
    }
  },
  methods: {
    // 获取表格数据
    async getTableData () {
      this.tableLoading = true
      const [ err, res ] = await this.preFetchTableData()
      this.tableLoading = false
      if (err) return this.$message.error(err.message || '获取数据出错')
      if (this.paginationBySelf) {
        this.allData = this.tableDataHandler(res.list)
        this.tableTotal = res.list.length
        this.paginationHandler()
      } else {
        this.tableData = this.tableDataHandler(res.list)
        this.tableTotal = res.total_num
      }
    },
    // 表格数据处理函数
    tableDataHandler (list) { return list },
    // 当前页面改变
    tableCurrentChange (currentPage) {
      this.page = String(currentPage)
      if (this.paginationBySelf) {
        this.paginationHandler()
      } else {
        this.getTableData()
      }
    },
    // 排序改变
    tableSortChange (data) {
      this.sort_field = data.prop
      this.sort_type = data.order === 'ascending' ? '0' : '1'
      this.getTableData()
    },
    // 选择框选择改变
    tableSelectionChange (selectList) {
      this.selectList = selectList
    },
    // 每页条数改变
    tableSizeChange (currentSize) {
      this.pageSize = String(currentSize)
      if (this.paginationBySelf) {
        this.paginationHandler()
      } else {
        this.getTableData()
      }
    },
    paginationHandler () {
      const startIndex = (this.page - 1) * Number(this.pageSize)
      const endIndex = startIndex + Number(this.pageSize)
      this.tableData = this.allData.slice(startIndex, endIndex)
      // 也算模拟调接口，重新调整页面
      this.$store.commit('ToogleApiComplete')
    }
  },
  created () {
    // 如果有搜索历史记录，数据将通过searchCondChange方法获取
    const history = this.pageSearchHistory.find(i => i.module === this.componentName)
    if (history && history.data && history.data.length) return
    this.getTableData()
  }
}

export default tableCoreMixin
